package com.zjsd.sqeybusiness.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.zjsd.sqeybusiness.domain.*;
import com.zjsd.sqeybusiness.dto.ShareparamDTO;
import com.zjsd.sqeybusiness.mapper.*;
import com.zjsd.sqeybusiness.service.ISjinfoService;
import com.zjsd.sqeybusiness.utils.WeChatAccessTokenUtil;
import com.zjsd.sqeybusiness.utils.WeChatNameGenerator;
import com.zjsd.sqeybusiness.utils.WeChatTemplateMessageUtil;
import com.zjsd.sqeybusiness.utils.WxSignatureUtil;
import javafx.geometry.Pos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 商机信息Service业务层处理
 * 
 * @author Zheng
 * @date 2025-03-06
 */
@Service
public class SjinfoServiceImpl implements ISjinfoService
{
    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SjinfoMapper sjinfoMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private DzsjinfoMapper dzsjinfoMapper;
    @Autowired
    private DzsjdetailMapper dzsjdetailMapper;
    @Autowired
    private DzsjprovincedetailMapper dzsjprovincedetailMapper ;
    @Autowired
    private HyinfoMapper hyinfoMapper ;
    @Autowired
    private WechatconfigMapper wechatconfigMapper ;
    @Autowired
    private PostsjinfoMapper postsjinfoMapper ;
    @Autowired
    private HydjinfoMapper hydjinfoMapper ;
    @Autowired
    private SysConfigMapper syconfigMapper;
    @Autowired
    private OrderinfoMapper orderinfoMapper ;

    /**
     * 查询商机信息
     * 
     * @param sjid 商机信息ID
     * @return 商机信息
     */
    @Override
    public Sjinfo selectSjinfoById(Long sjid)
    {
        return sjinfoMapper.selectSjinfoById(sjid);
    }

    /**
     * 查询商机信息列表
     * 
     * @param sjinfo 商机信息
     * @return 商机信息
     */
    @Override
    public List<Sjinfo> selectSjinfoList(Sjinfo sjinfo)
    {
        if(sjinfo.getEndDate() != null){
            Date endDate = sjinfo.getEndDate() ;
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endDate);
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            sjinfo.setEndDate(calendar.getTime());
        }
        List<Sjinfo> list = sjinfoMapper.selectSjinfoList(sjinfo);
        return list;
    }

    /**
     * 新增商机信息
     * 
     * @param sjinfo 商机信息
     * @return 结果
     */
    @Override
    public int insertSjinfo(Sjinfo sjinfo)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String tsbz = sjinfo.getTsbz();
        sjinfo.setCzrid(loginUser.getUser().getUserId());
        sjinfo.setCzsj(new Date());
        if(StringUtils.isNotEmpty(sjinfo.getProvincecode())){
            SysArea sysArea = sysAreaMapper.selectSysAreaByCode(sjinfo.getProvincecode());
            if(sysArea!=null){
                sjinfo.setProvincename(sysArea.getName());
            }
        }
        if(StringUtils.isNotEmpty(sjinfo.getCitycode())){
            SysArea sysArea = sysAreaMapper.selectSysAreaByCode( sjinfo.getCitycode());
            if(sysArea!=null){
                sjinfo.setCityname(sysArea.getName());
            }
        }
        if(StringUtils.isNotEmpty(sjinfo.getAreacode())){
            SysArea sysArea = sysAreaMapper.selectSysAreaByCode(sjinfo.getAreacode());
            if(sysArea!=null){
                sjinfo.setAreaname(sysArea.getName());
            }
        }
        if(StringUtils.isNotBlank(tsbz) && "0".equals(tsbz)){
            //操作时间往前提10分钟
            Date date = new Date();
            date.setTime(date.getTime() - 10 * 60 * 1000);
            sjinfo.setCzsj(date);
            if(sjinfo.getJdsl() != null ){
                for(long i= 1L ;i <= sjinfo.getJdsl(); i++){
                    Orderinfo orderinfo = new Orderinfo();
                    orderinfo.setSjid(sjinfo.getSjid());
                    orderinfo.setHyid(21L);
                    orderinfo.setHyphone("18663563979");
                    //随机生成一个微信名
                    String wxname = "wx" + UUID.randomUUID().toString().replace("-", "");
                    orderinfo.setWxname(WeChatNameGenerator.generateWeChatName());
                    orderinfo.setJdsl(1L);
                    orderinfo.setPrice(BigDecimal.ZERO);
                    orderinfo.setOpenid("ouJl66psaliGUDZek8uumARWqkJQ");
                    orderinfo.setZfzt("1");
                    orderinfo.setSszt("0");
                    orderinfo.setCzje(BigDecimal.ZERO);
                    orderinfoMapper.insertOrderinfo(orderinfo);
                }
            }
        }
        int i = sjinfoMapper.insertSjinfo(sjinfo);
        //推送模板消息
        if(StringUtils.isNotEmpty(tsbz) && "1".equals(tsbz)){
            this.sendMessage(sjinfo);
        }
        if(StringUtils.isNotBlank(tsbz) && "0".equals(tsbz)){
            if(sjinfo.getJdsl() != null ){
                for(long j= 1L ;j <= sjinfo.getJdsl(); j++){
                    Orderinfo orderinfo = new Orderinfo();
                    orderinfo.setSjid(sjinfo.getSjid());
                    orderinfo.setHyid(21L);
                    orderinfo.setHyphone("18663563979");
                    //随机生成一个微信名
                    String wxname = "wx" + UUID.randomUUID().toString().replace("-", "");
                    orderinfo.setWxname(WeChatNameGenerator.generateWeChatName());
                    orderinfo.setJdsl(1L);
                    orderinfo.setPrice(BigDecimal.ZERO);
                    orderinfo.setOpenid("ouJl66psaliGUDZek8uumARWqkJQ");
                    orderinfo.setZfzt("1");
                    orderinfo.setSszt("0");
                    orderinfo.setCzje(BigDecimal.ZERO);
                    Date date = new Date();
                    date.setTime(sjinfo.getCzsj().getTime() + 2 * 60 * 1000);
                    orderinfo.setJdsj(date);
                    orderinfoMapper.insertOrderinfo(orderinfo);
                }
            }
        }

        return  i ;
    }

    private void sendMessage(Sjinfo sjinfo) {
        String accessToken = WeChatAccessTokenUtil.getAccessToken(wechatconfigMapper);
        String templateId = Constants.KHYYCLTZ_TEMPLATE_ID;
        Hyinfo hyinfo3 = new Hyinfo();
        List<String> list3 = this.queryOpenidList(accessToken, "");
        List<Dzsjinfo> list5 = dzsjinfoMapper.selectDzsjinfoList(new Dzsjinfo());
        List<String> list4 = this.getUniqueIds(list3, list5);
        List<Dzsjinfo> list = dzsjinfoMapper.selectHyidBySjinfo(sjinfo);
        String url = Constants.DIRECT_URL + sjinfo.getSjid(); //跳转地址
        if(list != null && list.size() > 0){
            //执行计划
            ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
            Hydjinfo hydjinfo = new Hydjinfo();
            List<Hydjinfo> list1 = hydjinfoMapper.selectHydjinfoList(hydjinfo);
            //设置默认延迟时间
            Long ycsj = 500L ;
            SysConfig sysConfig =  syconfigMapper.selectSysConfigByKey("postmsg_ycsj");
            if(sysConfig != null){
                ycsj = StringUtils.isNotBlank(sysConfig.getConfigValue()) ?  Long.parseLong(sysConfig.getConfigValue()) :500L ;
            }
            for(Dzsjinfo dzsjinfo : list){
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Hyinfo hyinfo = hyinfoMapper.selectHyinfoById(dzsjinfo.getHyid());
                    if(hyinfo != null){
                        //普通会员
                        if(hyinfo.getHydjid() == null ){
                            System.out.println("【" + hyinfo.getHydjname() + "】执行推送，当前时间:" + sdf.format(new Date()));
                            executor.schedule(() -> {
                                String result = this.excuteSendMessage(accessToken, templateId, url, sjinfo, hyinfo, dzsjinfo);
                                Postsjinfo postsjinfo = new Postsjinfo();
                                postsjinfo.setSjid(sjinfo.getSjid());
                                postsjinfo.setHyid(hyinfo.getHyid());
                                postsjinfo.setHydjname(hyinfo.getHydjname());
                                postsjinfo.setOpenid(hyinfo.getOpenid());
                                postsjinfo.setTssj(new Date());
                                postsjinfo.setPostresult(result);
                                postsjinfo.setHydjid(hyinfo.getHydjid());
                                postsjinfo.setWxname(hyinfo.getWxname());
                                if(StringUtils.isNotEmpty(result) && result.contains("errcode")){
                                    JSONObject jsonObject = JSONObject.parseObject(result);
                                    postsjinfo.setErrcode(jsonObject.get("errcode").toString());
                                }
                                this.savePostsjinfo(postsjinfo);
                            }, ycsj, TimeUnit.SECONDS);
                        }else{
                            //充值会员，提前通知
                            if(list1 != null && list1.size() > 0){
                                for(Hydjinfo hydjinfo1 : list1){
                                    if(hydjinfo1.getHydjid().equals(hyinfo.getHydjid())){
                                        System.out.println("【" + hyinfo.getHydjname() + "】执行推送，提前" + hydjinfo1.getTqsj() + "秒执行，当前时间:" + sdf.format(new Date()));
                                        executor.schedule(() -> {
                                            String result =  this.excuteSendMessage(accessToken, templateId, url, sjinfo, hyinfo, dzsjinfo);
                                            Postsjinfo postsjinfo = new Postsjinfo();
                                            postsjinfo.setSjid(sjinfo.getSjid());
                                            postsjinfo.setHyid(hyinfo.getHyid());
                                            postsjinfo.setHydjname(hyinfo.getHydjname());
                                            postsjinfo.setOpenid(hyinfo.getOpenid());
                                            postsjinfo.setTssj(new Date());
                                            postsjinfo.setPostresult(result);
                                            postsjinfo.setHydjid(hydjinfo1.getHydjid());
                                            postsjinfo.setWxname(hyinfo.getWxname());
                                            if(StringUtils.isNotEmpty(result) && result.contains("errcode")){
                                                JSONObject jsonObject = JSONObject.parseObject(result);
                                                postsjinfo.setErrcode(jsonObject.get("errcode").toString());
                                            }
                                            this.savePostsjinfo(postsjinfo);
                                        }, ycsj - hydjinfo1.getTqsj(), TimeUnit.SECONDS);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("发送模板消息时发生错误", e);
                }
            }
        }

        if(list4 != null && list4.size() > 0){
            for(String openid : list4){
                    //等待2秒再执行
                    try {
                        System.out.println("关注人执行推送，推送会员ID：" + openid);
                        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
                        executor.schedule(() -> {
                            Hyinfo hyinfo = new Hyinfo();
                            hyinfo.setOpenid(openid);
                            List<Hyinfo> hyinfos = hyinfoMapper.selectHyinfoListByOpenid(hyinfo);
                            if(hyinfos != null && hyinfos.size() > 0){
                                hyinfo = hyinfos.get(0);
                            }
                            String result = this.excuteSendMessage(accessToken, templateId, url, sjinfo, hyinfo, new Dzsjinfo()) ;
                            Postsjinfo postsjinfo = new Postsjinfo();
                            postsjinfo.setSjid(sjinfo.getSjid());
                            postsjinfo.setHyid(hyinfo.getHyid());
                            postsjinfo.setHydjname(hyinfo.getHydjname());
                            postsjinfo.setOpenid(hyinfo.getOpenid());
                            postsjinfo.setTssj(new Date());
                            postsjinfo.setPostresult(result);
                            postsjinfo.setHydjid(hyinfo.getHydjid());
                            postsjinfo.setWxname(hyinfo.getWxname());
                            if(StringUtils.isNotEmpty(result) && result.contains("errcode")){
                                JSONObject jsonObject = JSONObject.parseObject(result);
                                postsjinfo.setErrcode(jsonObject.get("errcode").toString());
                            }
                            this.savePostsjinfo(postsjinfo);
                        }, 1, TimeUnit.SECONDS);
                    }catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
            }
        }



    }

    private List<String> queryOpenidList(String accessToken, String s){
        try {
            String result = WeChatAccessTokenUtil.getAccessOpenId(accessToken, s);
            if(StringUtils.isNotEmpty(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);
                if(jsonObject.containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONArray("openid");
                    List<String> list = new ArrayList<>();
                    for(int i = 0; i < jsonArray.size(); i++){
                        list.add(jsonArray.getString(i));
                    }
                    return list;
                }
            }
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }


    public static List<String> getUniqueIds(List<String> list1, List<Dzsjinfo> list2) {
        // 用于存储 list1 中的所有 ID
        Set<String> set1 = new HashSet<>();
        if(list1 != null && list1.size() > 0){
            for (String item : list1) {
                set1.add(item);
            }
        }

        // 用于存储 list2 中的所有 ID
        Set<String> set2 = new HashSet<>();
        if(list2 != null && list2.size() > 0){
            for (Dzsjinfo item : list2) {
                set2.add(item.getOpenid());
            }
        }
        // 存储不重复的 ID
        Set<String> uniqueIds = new HashSet<>();
        // 找出仅存在于 list1 中的 ID
        if(set1 != null && set1.size() > 0){
            for (String id : set1) {
                if (!set2.contains(id)) {
                    uniqueIds.add(id);
                }
            }
        }
        return new ArrayList<>(uniqueIds);
    }


    public String  excuteSendMessage(String accessToken, String templateId, String url, Sjinfo sjinfo , Hyinfo hyinfo , Dzsjinfo dzsjinfo) {
        String openId = hyinfo.getOpenid();
        JSONObject data = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(templateId.equals(Constants.DDTZ_TEMPLATE_ID)){
            //姓名
            data.put("thing1", new JSONObject().fluentPut("value", sjinfo.getCgrname()).fluentPut("color", "#173177"));
            //项目名称
            String title = sjinfo.getTitle().length() > 19 ? sjinfo.getTitle().substring(0,19) : sjinfo.getTitle();
            data.put("thing8", new JSONObject().fluentPut("value", title).fluentPut("color", "#173177"));
            //订单时间
            data.put("time9", new JSONObject().fluentPut("value", sdf.format(sjinfo.getFbsj())).fluentPut("color", "#173177"));
        }
        if(templateId.equals(Constants.KHYYCLTZ_TEMPLATE_ID)){
            //姓名
            data.put("thing1", new JSONObject().fluentPut("value", sjinfo.getCgrname()).fluentPut("color", "#173177"));
            //手机号
            String phone = sjinfo.getCgrphone().replaceAll("(\\d{3})\\d{8}(\\d{0})", "$1********$2");
            data.put("phone_number2", new JSONObject().fluentPut("value", phone).fluentPut("color", "#173177"));
            //项目名称
            System.out.println("标题：" + sjinfo.getTitle());
            String title = sjinfo.getTitle().length() > 19 ? sjinfo.getTitle().substring(0,19) : sjinfo.getTitle();
            data.put("thing5", new JSONObject().fluentPut("value", title).fluentPut("color", "#173177"));
            //预约时间
            data.put("time4", new JSONObject().fluentPut("value", sdf.format(sjinfo.getFbsj())).fluentPut("color", "#173177"));
        }
        String result = WeChatTemplateMessageUtil.sendTemplateMessage(accessToken, openId, templateId, url, data);
        System.out.println("推送结果：" + result);
        return result;
    }

    @Async
    public void savePostsjinfo(Postsjinfo postsjinfo) {
        try {
            // 设置超时时间
            if (!taskTimeout()) {
                throw new RuntimeException("任务超时");
            }
            System.out.println("保存结果：" + postsjinfo);
            int i = postsjinfoMapper.insertPostsjinfo(postsjinfo);
            System.out.println("保存结果成功：" + i);
        } catch (Exception e) {
            logger.error("保存 Postsjinfo 失败", e);
        }
    }

    private boolean taskTimeout() {
        // 模拟任务超时逻辑
        return true;
    }
    /**
     * 修改商机信息
     * 
     * @param sjinfo 商机信息
     * @return 结果
     */
    @Override
    public int updateSjinfo(Sjinfo sjinfo)
    {
        return sjinfoMapper.updateSjinfo(sjinfo);
    }

    /**
     * 批量删除商机信息
     * 
     * @param sjids 需要删除的商机信息ID
     * @return 结果
     */
    @Override
    public int deleteSjinfoByIds(Long[] sjids)
    {
        return sjinfoMapper.deleteSjinfoByIds(sjids);
    }

    /**
     * 删除商机信息信息
     * 
     * @param sjid 商机信息ID
     * @return 结果
     */
    @Override
    public int deleteSjinfoById(Long sjid)
    {
        return sjinfoMapper.deleteSjinfoById(sjid);
    }

    @Override
    public ShareparamDTO getShareparam(ShareparamDTO shareparamDTO) throws IOException {
        String accessToken = "";
        String ticket = "";
        Wechatconfig wechatconfig = wechatconfigMapper.selectWechatconfigById(1L);
        if(wechatconfig != null){
            accessToken =   WeChatAccessTokenUtil.getAccessToken(wechatconfigMapper);

            // 检查access_token是否过期
            if (wechatconfig.getTcssj() != null && wechatconfig.getTcssj().after(new Date()) && StringUtils.isNotBlank(wechatconfig.getTicket())) {
                ticket = wechatconfig.getTicket();
            }else{
                ticket = WxSignatureUtil.getJsapiTicket(accessToken);
                wechatconfig.setHqsj(new Date());
                wechatconfig.setTcssj(new Date(System.currentTimeMillis() + 7200000)); // 有效期为2小时
                wechatconfig.setYxsj(7200000L);
                wechatconfig.setTicket(ticket);
                wechatconfigMapper.updateWechatconfig(wechatconfig);
            }

        }
        ShareparamDTO shareparamDTO1 = WxSignatureUtil.getSignature(ticket , shareparamDTO);
        return shareparamDTO1;
    }
}
